package com.fuqi.android.zhongcai.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

/**
 * Created by wang on 2016/9/18.
 */
public class ImageCompressUtils {

    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeigh) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeigh || width > reqWidth) {
//            用Math.round转换float to int 取近似值，强制转换直接截取整数
            final int heightRatio = Math.round((float) height / (float) reqHeigh);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
//            取相对小的值，缩放比例越小，图片质量越高
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }

    public static Bitmap getSmallBitmap(String filePath, int reqWidth, int reqHeigh) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
//        解析图片，获取实际长宽
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
//      计算缩放比例
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeigh);
//        再次解析图片
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(filePath, options);
    }

}
